package me.webase.action;

import java.io.IOException;
import java.lang.reflect.Field;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.webase.service.Service;
import me.webase.util.GenericUtils;
import me.webase.util.JsonBuilder;
import me.webase.util.JsonUtil;
import me.webase.util.ModelUtil;
import me.webase.util.ResponseUtil;
import me.webase.util.json.JSONArray;
import me.webase.util.json.JSONException;
import me.webase.util.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ModelDriven;


public abstract class AbstractBaseAction<T> implements ModelDriven<T>{
	
	/**请求对象*/
	protected HttpServletRequest request = ServletActionContext.getRequest();
	/**返回对象*/
	protected HttpServletResponse response = ServletActionContext.getResponse();
	
	protected T model;
	
	protected Class<T> entityClass = GenericUtils.getSuperClassGenericType(getClass());
	@Resource
	protected Service service;
	/*每页数量*/
	private int limit;
	/*页码*/
	private int page;
	/*排序字段*/
	private String orderProperty;
	/*是否升序*/
	private boolean orderDirection; 
	/**
	 * 查询全部数据
	 */
	public void queryAll(){
		String s = null;
		try {
			if(limit <=0){
			 s = JsonUtil.bean2Json(service.queryAll(entityClass));
			} else { 
				 s = JsonUtil.bean2Json(service.pageQuery(entityClass, page, limit, orderDirection, orderProperty).getResult());
			}
			 
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ResponseUtil.response(s);
	}
	
	public void getModelFields(){
		Field[] fields = ModelUtil.getClassFields(entityClass, true);
		String s = JsonBuilder.getModelFileds("user", fields, "name");
		ResponseUtil.response(s);
	}
	
	
	protected void query(){
	}
	
	@Override
	public T getModel() {
		// TODO Auto-generated method stub
		return model;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}
	
	/**
	 * 处理排序字段形如  [{"property":"name","direction":"DESC"}]
	 * @param sort
	 */
	public void setSort(String sort){
		try {
			JSONArray jArr = new JSONArray(sort);
			JSONObject jObj =  jArr.getJSONObject(0);
			orderProperty = jObj.getString("property");
			
			String s = jObj.getString("direction");
			orderDirection = s.equals("ASC")?true:false;
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
